/*
 * @Description:
 * @Author: Rfan
 * @Date: 2022-05-30 15:56:42
 * @LastEditTime: 2022-06-16 18:45:59
 */

import { useEffect, useState } from 'react';
import { Button, Checkbox, Col, Divider, Form, Input, Radio, Row, Select, Space } from 'antd';
import classNames from 'classnames/bind';
import { useMetadataRelyContext } from '../../../contexts/MetadataRelyContext';
import type { ILevel } from '@/interfaces/archiveType';

import styles from '../../../styles/relyForm.module.scss';
import { selectItemByKey } from '@/utils/list';

const cx = classNames.bind(styles);

const { Option } = Select;

interface IRelyForm {
  changeRuleList: any;
}

const RelyForm = (props: IRelyForm) => {
  const { changeRuleList } = props;
  const { selectAT, selectLevel, levelMatedata, getLevelMetadata } = useMetadataRelyContext();
  const form = Form.useFormInstance();
  const { levelList }: { levelList: ILevel[] } = selectAT || [];

  const [selectLevelKey, setSelectLevelKey] = useState(null);

  useEffect(() => {
    if (selectLevel && selectLevel.level) {
      // const _level = jsonClone(selectLevel) && jsonClone(selectLevel).level + 1;
      getLevelMetadata(selectLevel.level);
    }
  }, [selectLevel]);

  // 层级下拉框切换
  const changeLevel = (value: number) => {
    setSelectLevelKey(value);
    getLevelMetadata(value);
  };

  // 拼接字符串
  const setStrsSplit = (desc: string | any, field: string, type: number) => {
    let str: string = '';
    const ruleItem: any = { type };
    if (type === 1) {
      str = `[${desc.levelName}:${desc.field_desc}]`;
      ruleItem.fieldValue = {
        field_desc: desc.field_desc,
        field_name: desc.field_name,
        level: selectLevelKey
      };
    } else {
      str = desc;
      ruleItem.strValue = desc;
    }
    form.setFieldsValue({ rule: (form.getFieldValue('rule') || '') + str });
    field && form.setFieldsValue({ [field]: '' });
    changeRuleList((state: any) => [...state, ruleItem]);
  };

  /**
   * @description: 通用增加字符串方法
   * @param {string} field 更新之后需要清空的表单
   */
  const setStrs = (field?: string) => {
    const value = form.getFieldValue(field);

    if (value) {
      setStrsSplit(value, field, 0);
    }
  };

  /**
   * @description: 拼接字段
   */
  const joinFieldStr = () => {
    const id = form.getFieldValue('condField');
    if (selectLevelKey && id) {
      const levelItem: any = selectItemByKey(selectLevelKey, levelList, 'level');
      const field: any = selectItemByKey(id, levelMatedata[selectLevel.level]);
      console.log({ id, levelItem, field });

      field.levelName = levelItem.levelName;
      setStrsSplit(field, 'condField', 1);
    }
  };

  /**
   * @description: 清空规则方法
   */
  const clearRules = () => {
    form.setFieldsValue({ rule: '' });
    changeRuleList([]);
  };

  return (
    <>
      <Form.Item name="isValid" label="状态">
        <Radio.Group>
          <Radio value={0}>启用</Radio>
          <Radio value={1}>停用</Radio>
        </Radio.Group>
      </Form.Item>
      <Form.Item label="字段" required>
        <Form.Item
          name="targetDataId"
          label={selectLevel.levelName}
          colon={false}
          rules={[{ required: true }]}
          required={false}
        >
          <Select>
            {(levelMatedata[selectLevel.level] || []).map((item: any) => (
              <Option key={item.id} value={item.id}>
                {item.field_desc}
              </Option>
            ))}
          </Select>
        </Form.Item>
      </Form.Item>
      <Form.Item label="依赖规则" colon={false} required></Form.Item>
      <div className={cx('rely-wrap')}>
        <Form.Item label="拼接结果" required>
          <Row>
            <Col flex="auto">
              <Form.Item name="rule" rules={[{ required: true, message: '请拼接依赖规则' }]}>
                <Input disabled />
              </Form.Item>
            </Col>
            <Col className={cx('button-wrap')} flex="80px">
              <Button
                type="primary"
                onClick={() => {
                  clearRules();
                }}
              >
                清空
              </Button>
            </Col>
          </Row>
        </Form.Item>
        <Divider />
        <Form.Item label="依赖字段">
          <Row>
            <Col flex="auto">
              <Space>
                <Form.Item label="层级">
                  <Select style={{ width: '100px' }} onChange={changeLevel}>
                    {levelList.map((item: ILevel) => (
                      <Option key={item.level} value={item.level}>
                        {item.levelName}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
                <Form.Item name="condField" label="字段">
                  <Select style={{ width: '110px' }}>
                    {(levelMatedata[selectLevelKey] || []).map((item: any) => (
                      <Option key={item.id} value={item.id}>
                        {item.field_desc}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Space>
            </Col>
            <Col className={cx('button-wrap')} flex="80px">
              <Button type="primary" onClick={joinFieldStr}>
                拼接
              </Button>
            </Col>
          </Row>
        </Form.Item>
        <Form.Item label="连接符">
          <Row>
            <Col flex="auto">
              <Form.Item name="condMark" noStyle>
                <Input />
              </Form.Item>
            </Col>
            <Col className={cx('button-wrap')} flex="80px">
              <Button
                type="primary"
                onClick={() => {
                  setStrs('condMark');
                }}
              >
                拼接
              </Button>
            </Col>
          </Row>
        </Form.Item>
        <Form.Item label="输入字符串">
          <Row>
            <Col flex="auto">
              <Form.Item name="constStr" noStyle>
                <Input />
              </Form.Item>
            </Col>
            <Col className={cx('button-wrap')} flex="80px">
              <Button
                type="primary"
                onClick={() => {
                  setStrs('constStr');
                }}
              >
                拼接
              </Button>
            </Col>
          </Row>
        </Form.Item>
        <Form.Item name="isLinkage" label="数据联动" valuePropName="checked">
          <Checkbox>与依赖字段联动</Checkbox>
        </Form.Item>
      </div>
    </>
  );
};

export default RelyForm;
